<template>
  <div class="article-list-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1>{{ pageConfig.title }}</h1>
        <p class="subtitle">{{ pageConfig.subtitle }}</p>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="container">
      <!-- 面包屑导航 -->
      <Breadcrumb />
      
      <div class="main-content">
        <!-- 页面提示 -->
        <el-alert
          :title="pageConfig.alertTitle"
          :type="pageConfig.alertType || 'info'"
          :closable="false"
          show-icon
          class="notice-alert"
          v-if="pageConfig.alertTitle"
        >
          <template #default>
            <div class="notice-content">
              <p v-for="(tip, index) in pageConfig.tips" :key="index" v-html="tip"></p>
            </div>
          </template>
        </el-alert>

        <!-- 筛选条件 -->
        <el-card class="filter-card" shadow="never" v-if="enableSearch">
          <el-form :inline="true" :model="filterForm">
            <el-form-item label="关键词搜索">
              <el-input 
                v-model="filterForm.keyword" 
                placeholder="请输入关键词" 
                clearable 
                style="width: 200px"
                @input="debounceSearch"
              />
            </el-form-item>
            <el-form-item label="标签筛选" v-if="availableTags.length > 0">
              <el-select 
                v-model="filterForm.tag" 
                placeholder="选择标签" 
                clearable 
                style="width: 150px"
                @change="loadArticles"
              >
                <el-option 
                  v-for="tag in availableTags" 
                  :key="tag" 
                  :value="tag" 
                  :label="tag" 
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadArticles">搜索</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 文章列表 -->
        <el-card class="articles-card" shadow="never" v-loading="loading">
          <template #header>
            <div class="card-header">
              <h2><el-icon><Document /></el-icon> {{ pageConfig.listTitle || '文章列表' }}</h2>
              <div class="header-info">
                <el-tag type="info">
                  <el-icon><InfoFilled /></el-icon>
                  共 {{ pagination.total }} 篇文章
                </el-tag>
              </div>
            </div>
          </template>

          <!-- 文章列表内容 -->
          <div class="articles-list" v-if="articles.length > 0">
            <div 
              v-for="article in articles" 
              :key="article.id" 
              class="article-item"
              @click="goToArticleDetail(article.id)"
            >
              <div class="article-content">
                <div class="article-header">
                  <h3 class="article-title">
                    <el-link :underline="false" @click="goToArticleDetail(article.id)">
                      {{ article.title }}
                    </el-link>
                  </h3>
                  <div class="article-meta">
                    <span class="tags" v-if="article.tags">
                      <el-tag 
                        v-for="tag in getArticleTags(article.tags)" 
                        :key="tag" 
                        size="small" 
                        type="primary"
                      >
                        {{ tag }}
                      </el-tag>
                    </span>
                  </div>
                </div>
                
                <div class="article-summary" v-if="article.summary">
                  <p>{{ article.summary }}</p>
                </div>
                
                <div class="article-footer">
                  <div class="article-info">
                    <span class="publish-time">
                      <el-icon><Clock /></el-icon>
                      {{ formatDate(article.createdAt) }}
                    </span>
                    <span class="view-count" v-if="article.viewCount">
                      <el-icon><View /></el-icon>
                      {{ article.viewCount }}
                    </span>
                    <span class="author" v-if="article.author">
                      <el-icon><User /></el-icon>
                      {{ article.author }}
                    </span>
                  </div>
                  <div class="article-actions">
                    <el-button type="primary" size="small" @click.stop="goToArticleDetail(article.id)">
                      查看详情
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <el-empty 
            v-else-if="!loading"
            description="暂无相关文章"
            :image-size="120"
          />

          <!-- 分页 -->
          <div class="pagination-wrapper" v-if="pagination.total > 0">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePageChange"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>

        <!-- 补充说明 -->
        <el-card class="tips-card" shadow="never" v-if="pageConfig.extraTips">
          <template #header>
            <h2><el-icon><QuestionFilled /></el-icon> {{ pageConfig.extraTips.title }}</h2>
          </template>
          <div class="tips-content">
            <el-row :gutter="20">
              <el-col :span="12" v-for="(section, index) in pageConfig.extraTips.sections" :key="index">
                <h3>{{ section.title }}</h3>
                <ul>
                  <li v-for="(item, itemIndex) in section.items" :key="itemIndex">{{ item }}</li>
                </ul>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, defineProps } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  InfoFilled, 
  Clock, 
  View, 
  User,
  QuestionFilled 
} from '@element-plus/icons-vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import api from '@/api'

// Props
const props = defineProps({
  // 文章分类ID
  categoryId: {
    type: Number,
    required: true
  },
  // 页面配置
  pageConfig: {
    type: Object,
    required: true
  },
  // 是否启用搜索
  enableSearch: {
    type: Boolean,
    default: true
  },
  // 可用标签
  availableTags: {
    type: Array,
    default: () => []
  },
  // 模拟数据（用于演示）
  mockData: {
    type: Array,
    default: () => []
  }
})

const router = useRouter()

// 响应式数据
const loading = ref(false)
const articles = ref([])

const filterForm = reactive({
  keyword: '',
  tag: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

let searchTimeout = null

// 方法
const loadArticles = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      categoryId: props.categoryId
    }
    
    // 添加搜索条件
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword
    }
    if (filterForm.tag) {
      params.tag = filterForm.tag
    }
    
    const { data } = await api.get('/articles', { params })
    articles.value = data.records || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('加载文章失败:', error)
    // 使用模拟数据
    loadMockArticles()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
const loadMockArticles = () => {
  let filteredArticles = [...props.mockData]
  
  // 应用搜索筛选
  if (filterForm.keyword) {
    filteredArticles = filteredArticles.filter(article => 
      article.title.includes(filterForm.keyword) || 
      (article.summary && article.summary.includes(filterForm.keyword))
    )
  }
  
  if (filterForm.tag) {
    filteredArticles = filteredArticles.filter(article => 
      article.tags && article.tags.includes(filterForm.tag)
    )
  }
  
  // 分页
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  articles.value = filteredArticles.slice(start, end)
  pagination.total = filteredArticles.length
}

// 防抖搜索
const debounceSearch = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    pagination.page = 1
    loadArticles()
  }, 500)
}

const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    tag: ''
  })
  pagination.page = 1
  loadArticles()
}

const handlePageChange = () => {
  loadArticles()
}

const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const getArticleTags = (tags) => {
  if (!tags) return []
  return typeof tags === 'string' ? tags.split(',') : tags
}

const goToArticleDetail = (articleId) => {
  router.push(`/articles/${articleId}`)
}

// 初始化
onMounted(() => {
  loadArticles()
})
</script>

<style lang="scss" scoped>
.article-list-page {
  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 60px 0;
    text-align: center;
    
    h1 {
      font-size: 2.5rem;
      margin-bottom: 16px;
      font-weight: 600;
    }
    
    .subtitle {
      font-size: 1.2rem;
      opacity: 0.9;
    }
  }
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  .main-content {
    margin-top: -40px;
    position: relative;
    z-index: 1;
    
    .el-card {
      margin-bottom: 30px;
      border-radius: 12px;
      
      .el-card__header {
        background: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
        
        h2 {
          margin: 0;
          color: #495057;
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }
  }
  
  .notice-alert {
    margin-bottom: 20px;
    
    .notice-content {
      p {
        margin: 8px 0;
        font-size: 14px;
        line-height: 1.6;
        
        &:first-child {
          margin-top: 0;
        }
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  .filter-card {
    .el-form {
      margin: 0;
    }
  }
  
  .articles-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-info {
        .el-tag {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
    
    .articles-list {
      .article-item {
        padding: 24px;
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        margin-bottom: 16px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #409eff;
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
          transform: translateY(-2px);
        }
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      .article-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
        
        .article-title {
          flex: 1;
          margin: 0 20px 0 0;
          
          .el-link {
            font-size: 18px;
            font-weight: 500;
            color: #303133;
            line-height: 1.4;
            
            &:hover {
              color: #409eff;
            }
          }
        }
        
        .article-meta {
          display: flex;
          gap: 8px;
          flex-shrink: 0;
          
          .tags {
            display: flex;
            gap: 4px;
          }
        }
      }
      
      .article-summary {
        margin-bottom: 16px;
        
        p {
          margin: 0;
          color: #606266;
          line-height: 1.6;
          font-size: 14px;
        }
      }
      
      .article-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .article-info {
          display: flex;
          gap: 16px;
          font-size: 13px;
          color: #909399;
          
          span {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }
    }
    
    .pagination-wrapper {
      margin-top: 24px;
      text-align: center;
    }
  }
  
  .tips-card {
    .tips-content {
      h3 {
        margin-top: 0;
        margin-bottom: 16px;
        color: #2c3e50;
        font-size: 16px;
      }
      
      ul {
        padding-left: 20px;
        
        li {
          margin-bottom: 8px;
          line-height: 1.6;
          color: #6c757d;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .article-list-page {
    .page-header {
      padding: 40px 0;
      
      h1 {
        font-size: 2rem;
      }
      
      .subtitle {
        font-size: 1rem;
      }
    }
    
    .filter-card {
      .el-form {
        .el-form-item {
          display: block;
          margin-right: 0;
          margin-bottom: 16px;
        }
      }
    }
    
    .articles-card {
      .articles-list {
        .article-item {
          padding: 16px;
        }
        
        .article-header {
          flex-direction: column;
          gap: 12px;
          align-items: flex-start;
          
          .article-title {
            margin-right: 0;
            
            .el-link {
              font-size: 16px;
            }
          }
        }
        
        .article-footer {
          flex-direction: column;
          gap: 12px;
          align-items: flex-start;
          
          .article-info {
            flex-direction: column;
            gap: 8px;
          }
        }
      }
    }
    
    .tips-card {
      .tips-content {
        .el-row {
          .el-col {
            margin-bottom: 20px;
          }
        }
      }
    }
  }
}
</style>